﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using UnityEditor;
using UnityEngine;

[Editor]
public class PanerlManager : MonoBehaviour
{
    //宽 高
    public int widthCount = 1;
    public int heightCount = 1;
    
    public Vector2 size = Vector2.one;
    public GameObject perfab;


    public Vector2 startPos = new Vector2(-100,-100);
    
    
   public List<Panel> _panels = new List<Panel>();


   public List<PanelSprite> panelSprites;
   public Dictionary<RoadType,Sprite> _dict = new Dictionary<RoadType, Sprite>();
   [Serializable]
   public class PanelSprite
   {
       public RoadType roadType;
       public Sprite sprite;
   }

   /// <summary>
   /// 获取图片通过道路类型
   /// </summary>
   /// <param name="roadType"></param>
   /// <returns></returns>
   public Sprite GetSpriteBy(RoadType roadType)
   {
       Init();//初始化
       Sprite sprite =null;
       _dict.TryGetValue(roadType, out sprite);
       return sprite;
   }
   
   

   /// <summary>
   /// 初始化数据
   /// </summary>
   void Init()
   {
       if (panelSprites != null && panelSprites.Count>0)
       {
           foreach (var panel in panelSprites)
           {
               if (!_dict.ContainsKey(panel.roadType))
               {
                   _dict.Add(panel.roadType,panel.sprite);
               }
           }
       }
       
   }
   
    public Transform parent;


    /// <summary>
    /// 创建
    /// </summary>
    public void Create()
    {
        if(_dict!=null) _dict.Clear();
        if (_panels.Count < widthCount * heightCount)
        {
            for (int i = 0; i < widthCount; i++)
            {
                for (int j = 0; j < heightCount; j++)
                {
                    Vector2 index = new Vector2(i,j);
                    AutoCreatePanel(Vector3.zero, index,Vector2.zero);
                }
            }   
        }
        UpdateView();
    }

    /// <summary>
    /// 清除
    /// </summary>
    public void ClearAll()
    {
        while (_panels.Count>0)
        {
            AutoKillPanel();
        }
        AssetDatabase.Refresh();
    }
    
    private void OnValidate()
    {
        UpdateView();
    }

    /// <summary>
    /// 创建面板
    /// </summary>
    /// <param name="pos"></param>
    /// <param name="index"></param>
    /// <param name="baseIndex"></param>
    void AutoCreatePanel(Vector3 pos, Vector2 index,Vector2 baseIndex)
    {
        GameObject p = Instantiate(perfab, Vector3.zero, Quaternion.identity,parent);
        p.GetComponent<Panel>().SetPoint(baseIndex,index);//索引点
        p.GetComponent<Panel>().panerlManager = this;
        p.GetComponent<Panel>().SetPanelId(index.x+"x"+index.y);
        p.gameObject.SetActive(true);
        _panels.Add(p.GetComponent<Panel>());
    }

    
    /// <summary>
    /// 自动清除
    /// </summary>
    void AutoKillPanel()
    {
        if(_panels.Count <=0) return;
        Panel p = _panels[_panels.Count - 1];
        _panels.Remove(p);
        DestroyImmediate(p.gameObject);
    }

    void Refesh()
    {
        if (_panels.Count > 0)
        {
            foreach (var panel in _panels)
            {
                panel.OnValidate();
                EditorUtility.SetDirty(panel);//刷新
            }   
        }
    }
    
    /// <summary>
    /// 更新展示
    /// </summary>
    void UpdateView()
    {
        if (_panels != null && _panels.Count > 0)
        {
            Panel temp = null;
            for (int i = 0; i < _panels.Count; i++)
            {
                temp = _panels[i];
                temp.GetComponent<RectTransform>().anchoredPosition =
                    temp.GetPoint * size - startPos * size;
            }
        }
    }

    

    public string fileName = "panel";
    public int index = 1;
    
    
    
    /// <summary>
    /// 数据
    /// </summary>
    [Serializable]
    public class Data
    {
        [SerializeField] private List<Panel.DataClass> list;

        public List<Panel.DataClass> GetData
        {
            get
            {
                return list;
            }
        }
        
        public Data()
        {
            list = new List<Panel.DataClass>();
        }
        
        public Data(List<Panel.DataClass> list)
        {
            this.list = list;
        }

        public void Add(Panel.DataClass dataClass)
        {
            list.Add(dataClass);
        }

        public int GetCount
        {
            get
            {
                return list.Count;
            }
        }

        public void Clear()
        {
            list.Clear();
        }
    }
    
    public string Path =>Application.dataPath + "/"+fileName+index+".json";
    
    
    //导出数据
    public void OutPutFile()
    {
        Data data = new Data();

        foreach (var panel in _panels)
        {
            data.Add(panel.ExportData());
        }
        
        if(data.GetCount <=0) return;
        Debug.Log("aaa");
        string json = JsonUtility.ToJson(data);
        Debug.Log("json" + json + "--->" + data.GetCount);
        
        //将数据导出
        if (!File.Exists(Path))
        {
            File.Create(Path);
        }
        File.WriteAllText(Path,json);
        Debug.Log("保存成功！-->"+ Path);
    }
    
    
    
    public void ReadInFile()
    {
        string path =Application.dataPath + "/"+fileName+index+".json";
        //将数据导出
        if (File.Exists(path))
        {
            //进行读入
            string str = File.ReadAllText(path);

            Data data = JsonUtility.FromJson<Data>(str);
            //将数据解析出来
            
            Debug.Log(_panels.Count +" :" + data.GetCount);
            
            //根据当前的位置进行摆放
           
            while (_panels.Count!=data.GetCount)
            {
                if (_panels.Count < data.GetCount)
                {
                    //创造
                    AutoCreatePanel(Vector3.zero, Vector2.zero, Vector2.zero);
                }
                
                else if (_panels.Count > data.GetCount)
                {
                    AutoKillPanel();
                }
            }





            Panel.DataClass dataClassTemp;
            //部署内容
            for (int i = 0; i < _panels.Count; i++)
            {
                dataClassTemp = data.GetData[i];
                _panels[i].LoadData(dataClassTemp);
                if (!_panelsDictionary.ContainsKey(dataClassTemp.Id))
                {
                    _panelsDictionary.Add(dataClassTemp.Id,_panels[i]);
                }
            }
            
            
            //设置父物体
            foreach (var panel in _panels)
            {
                if (panel.GetDataClass.baseLockId != "")
                {
                    Panel penelTamp;
                    _panelsDictionary.TryGetValue(panel.GetDataClass.baseLockId,out penelTamp);
                    panel.SetBaseLockPanel(penelTamp);
                }
            }
            
            
            
            Debug.Log("加载完成");
            Refesh();
        }
    }
    
    Dictionary<string,Panel> _panelsDictionary = new Dictionary<string, Panel>();


}
